<template>
    <div class="white-box-form">
        <el-form
            ref="ruleRef"
            :model="state.ruleForm"
            :rules="state.rules"
            label-width="120px"
            class="mt-20"
        >
            <el-form-item label="手机号" prop="phone">
                <el-input
                    v-model.trim="state.ruleForm.phone"
                    clearable
                    maxlength="11"
                    placeholder="请输入手机号"
                />
            </el-form-item>
            <el-form-item v-if="!isEdit" label="密码" prop="password">
                <el-input
                    v-model.trim="state.ruleForm.password"
                    autocomplete="new-password"
                    maxlength="20"
                    type="password"
                    show-password
                    clearable
                    placeholder="请输入密码"
                />
            </el-form-item>
            <el-form-item label="所属角色" prop="roleSids">
                <el-select
                    v-model="state.ruleForm.roleSids"
                    placeholder="请选择所属角色"
                    clearable
                    multiple
                >
                    <el-option
                        v-for="item in state.roleOptions"
                        :key="item.sid"
                        :label="item.roleName"
                        :value="item.sid"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="所属网点" prop="outletsSid">
                <el-tree-select
                    v-model="state.ruleForm.outletsSid"
                    :data="state.outletsOptions"
                    filterable
                    check-strictly
                    placeholder="请选择所属网点"
                    :clearable="!isEdit"
                    :props="{ value: 'sid', label: 'outletsName' }"
                />
            </el-form-item>
            <el-form-item label="员工名称" prop="userName">
                <el-input
                    v-model.trim="state.ruleForm.userName"
                    clearable
                    maxlength="20"
                    placeholder="请输入员工名称"
                />
            </el-form-item>
            <el-form-item label="昵称" prop="nickName">
                <el-input
                    v-model.trim="state.ruleForm.nickName"
                    max-length="20"
                    clearable
                    placeholder="请输入昵称"
                />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input
                    v-model.trim="state.ruleForm.email"
                    clearable
                    placeholder="请输入邮箱"
                />
            </el-form-item>
            <el-form-item label="生日" prop="birth">
                <el-date-picker
                    v-model="state.ruleForm.birth"
                    type="date"
                    :disabled-date="disabledDate"
                    format="YYYY/MM/DD"
                    :clearable="false"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择生日"
                />
            </el-form-item>
            <el-form-item label="备注" prop="note">
                <el-input
                    v-model.trim="state.ruleForm.note"
                    type="textarea"
                    maxlength="100"
                    :autosize="{ minRows: 2 }"
                    clearable
                    show-word-limit
                    placeholder="请输入备注"
                />
            </el-form-item>
            <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="state.ruleForm.sex">
                    <el-radio
                        v-for="item in state.sexList"
                        :key="item.memberKey"
                        :value="item.memberKey"
                        >{{ item.memberName }}</el-radio
                    >
                </el-radio-group>
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-radio-group v-model="state.ruleForm.status">
                    <el-radio
                        v-for="item in state.statusList"
                        :key="item.memberKey"
                        :value="item.memberKey"
                        >{{ item.memberName }}</el-radio
                    >
                </el-radio-group>
            </el-form-item>
            <el-form-item label="头像" prop="avatar">
                <el-upload
                    ref="uploadRef"
                    v-model:file-list="fileList"
                    v-loading="imgLoading"
                    :limit="1"
                    :class="{
                        'hide-upload-btn': state.ruleForm.avatar,
                    }"
                    :action="actionImgUrl()"
                    :http-request="uploadImg"
                    list-type="picture-card"
                    :on-remove="handleRemove"
                    :before-upload="beforeAvatarUpload"
                    :on-change="fileChange"
                    :on-preview="handlePreview"
                    :on-exceed="handleExceed"
                >
                    <el-icon color="#999">
                        <upload-filled />
                    </el-icon>
                </el-upload>
            </el-form-item>
        </el-form>

        <div class="foot-btn">
            <el-button
                type="primary"
                :loading="state.form_loading"
                @click="submitForm(ruleRef)"
            >
                {{ isEdit ? "修改" : "添加" }}
            </el-button>
        </div>

        <go-back />
    </div>

    <el-dialog v-model="imgVisible">
        <img w-full :src="dialogImageUrl" />
    </el-dialog>
</template>

<script setup>
import { inject, ref, onMounted, reactive, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import GoBack from "@components/GoBack.vue";

import JSEncrypt from "jsencrypt";
import UploadImg from "@/mixins/upload-img";
import { validPhone } from "@/assets/common/utils";
import { getUserDetail, addUser, editUser } from "@/apis/user/user";
import { getStaffRolesAll } from "@/apis/system/role";
import { getOutletsAll } from "@/apis/outlet/outlet";
import { getEncrypt } from "@/apis/login";
import { useDictStore } from "@stores/dict.js";

const dictStore = useDictStore();
dictStore.getDictMembers("data_status").then((res) => (state.statusList = res));
dictStore.getDictMembers("sex").then((res) => (state.sexList = res));

const router = useRouter();
const route = useRoute();

const $message = inject("$message");
const imgUrl = inject("imgUrl");

const sid = route.query.sid;
const isEdit = ref(false);
const ruleRef = ref(null);
const validPassword = (rule, value, callback) => {
    let regu = /^[a-zA-Z0-9!@#$%^&*_]{6,20}$/;
    if (!regu.test(value)) {
        callback(new Error("密码只能由6-20位数字字母以及 !@#$%^&*_ 组成"));
    } else {
        callback();
    }
};
const state = reactive({
    statusList: [],
    sexList: [],
    pub_keys: "",
    outletsOptions: [],
    roleOptions: [],
    ruleForm: {
        avatar: null,
        birth: null,
        email: null,
        nickName: null,
        note: null,
        outletsSid: null,
        password: null,
        phone: null,
        roleSids: [],
        sex: 2,
        status: 0,
        userName: null,
    },
    rules: {
        password: [
            { required: true, validator: validPassword, trigger: "blur" },
        ],
        phone: [{ required: true, validator: validPhone, trigger: "blur" }],
        roleSids: [
            { required: true, message: "请选择所属角色", trigger: "blur" },
        ],
        outletsSid: [
            { required: true, message: "请选择所属网点", trigger: "blur" },
        ],
    },
    form_loading: false,
});

onMounted(async () => {
    await Promise.allSettled([getRoleOptions(), getOutletsOptions()]);
    if (/Edit$/.test(route.name)) {
        isEdit.value = true;
        getDetail();
    }
});

const getOutletsOptions = async () => {
    const res = await getOutletsAll();
    if (res.data.code == 200) {
        state.outletsOptions = res.data.data;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

const getRoleOptions = async () => {
    const res = await getStaffRolesAll();
    if (res.data.code == 200) {
        state.roleOptions = res.data.data;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

const getDetail = async () => {
    const res = await getUserDetail({ sid });
    if (res.data.code == 200) {
        state.ruleForm = res.data.data;
        if (state.ruleForm.avatar) {
            const arr = state.ruleForm.avatar.split("/");
            fileList.value.push({
                name: arr[arr.length - 1],
                url: imgUrl + state.ruleForm.avatar,
            });
        }
        state.ruleForm.roleSids = getRoleSids(state.ruleForm.roleKeySet);
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

const getRoleSids = (roleKeySet) => {
    return roleKeySet.reduce((pre, cur) => {
        const role = state.roleOptions.find((item) => item.roleKey === cur);
        if (role) pre.push(role.sid);
        return pre;
    }, []);
};

const disabledDate = (time) => {
    return time.getTime() > Date.now();
};

const getKey = async () => {
    const res = await getEncrypt();
    if (res.data.code == 200) {
        state.pub_keys = res.data.data;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

const submitForm = (formEl) => {
    if (!formEl) return;
    formEl.validate(async (valid, fields) => {
        if (valid) {
            state.form_loading = true;

            let res = null;
            state.ruleForm.email = state.ruleForm.email || null;
            if (isEdit.value) {
                // 修改
                res = await editUser(state.ruleForm);
            } else {
                // 新增
                await getKey();
                let encryptor = new JSEncrypt(); // 创建加密对象实例
                encryptor.setPublicKey(state.pub_keys); // 设置公钥
                let password = encryptor.encrypt(state.ruleForm.password); // 对内容进行加密
                res = await addUser({ ...state.ruleForm, password });
            }
            state.form_loading = false;
            if (res.data.code == 200) {
                $message({
                    message: isEdit.value ? "修改成功" : "添加成功",
                    type: "success",
                });
                router.back();
            } else {
                $message({ message: res.data.msg, type: "error" });
            }
        }
    });
};

const uploadRef = ref(null);
const {
    succList,
    imgLoading,
    handlePreview,
    actionImgUrl,
    uploadImg,
    handleRemove,
    beforeAvatarUpload,
    fileChange,
    handleExceed,
    imgVisible,
    dialogImageUrl,
    fileList,
} = UploadImg();
watch(
    succList,
    (newVal) => {
        state.ruleForm.avatar = newVal.length ? newVal[0] : "";
    },
    { deep: true }
);
</script>
